package com.yixin.hospital.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.domain.AuditFlow;
import com.yixin.hospital.entity.domain.AuditFlowDetail;
import com.yixin.hospital.entity.domain.Message;
import com.yixin.hospital.entity.dto.req.auditmanager.PurchaseOrderAuditReqDTO;
import com.yixin.hospital.enums.*;
import com.yixin.hospital.service.AuditFlowDetailService;
import com.yixin.hospital.service.AuditFlowService;
import com.yixin.hospital.service.MessageService;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/audit-manager")
@Api(value = "审批管理", tags = "审批管理")
public class AuditManagerController {
    @Resource
    AuditFlowDetailService auditFlowDetailService;
    @Resource
    AuditFlowService auditFlowService;
    @Resource
    MessageService messageService;

    @PostMapping("/audit")
    @ApiOperation(value = "审批")
    @Transactional
    public ApiResult<?> audit(@Valid @RequestBody PurchaseOrderAuditReqDTO drugPutBillAuditReqDTO, HttpServletRequest request) {
        Long userId = JwtUtil.getUserId(request.getHeader(Constant.AUTHORIZATION));
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        LambdaQueryWrapper<AuditFlowDetail> aWrapper = new LambdaQueryWrapper<>();
        aWrapper.eq(AuditFlowDetail::getFlowNo, drugPutBillAuditReqDTO.getFlowNo());
        aWrapper.eq(AuditFlowDetail::getStatus, AuditDetailStatusEnum.AUDIT_ME.getCode());
        AuditFlowDetail auditFlowDetail = auditFlowDetailService.getOne(aWrapper);
        if (auditFlowDetail == null) {
            return ApiResult.error();
        }
        if (!Objects.equals(auditFlowDetail.getStatus(), AuditDetailStatusEnum.AUDIT_ME.getCode())) {
            return ApiResult.error();
        }

        if (!auditFlowDetail.getAuditUserId().equals(userId)) {
            return ApiResult.error(ResponseCodeEnum.ILLEGAL_AUTH);
        }

        // 修改审批详情表
        auditFlowDetail.setStatus(drugPutBillAuditReqDTO.getPass() ? AuditDetailStatusEnum.FINISH.getCode() : AuditDetailStatusEnum.REJECT.getCode());
        auditFlowDetail.setUpdatedBy(userName);
        auditFlowDetail.setAuditTime(new Date());
        LambdaUpdateWrapper<AuditFlowDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AuditFlowDetail::getId, auditFlowDetail.getId());
        updateWrapper.eq(AuditFlowDetail::getStatus, AuditDetailStatusEnum.AUDIT_ME.getCode());
        auditFlowDetailService.update(auditFlowDetail, updateWrapper);

        // 查询是否有下一级审批
        LambdaQueryWrapper<AuditFlowDetail> nextWrapper = new LambdaQueryWrapper<>();
        nextWrapper.eq(AuditFlowDetail::getFlowNo, drugPutBillAuditReqDTO.getFlowNo());
        nextWrapper.eq(AuditFlowDetail::getStatus, AuditDetailStatusEnum.AUDITING.getCode());
        nextWrapper.orderByAsc(AuditFlowDetail::getSort);
        List<AuditFlowDetail> nextAuditFlowDetailList = auditFlowDetailService.list(nextWrapper);

        // 有下一级审批
        if (!nextAuditFlowDetailList.isEmpty() && drugPutBillAuditReqDTO.getPass()) {
            AuditFlowDetail nextAuditFlowDetail = nextAuditFlowDetailList.get(0);
            LambdaUpdateWrapper<AuditFlowDetail> upWrapper = new LambdaUpdateWrapper<>();
            upWrapper.eq(AuditFlowDetail::getId, nextAuditFlowDetail.getId());
            upWrapper.eq(AuditFlowDetail::getStatus, AuditDetailStatusEnum.AUDITING.getCode());
            nextAuditFlowDetail.setStatus(AuditDetailStatusEnum.AUDIT_ME.getCode());
            auditFlowDetailService.update(nextAuditFlowDetail, upWrapper);

            // 发送通知
            Message message = new Message();
            message.setMessageType(MessageTypeEnum.getDesc(auditFlowDetail.getFlowNo().substring(0, 2)));
            message.setUserId(nextAuditFlowDetail.getAuditUserId());
            message.setContent(FlowNoPrefixEnum.getDesc(auditFlowDetail.getFlowNo().substring(0, 2)));
            message.setStatus(0);
            message.setCreatedBy(userName);
            message.setUpdatedBy(userName);
            messageService.save(message);
            return ApiResult.success();
        }

        // 无下一级审批
        AuditFlow auditFlow = new AuditFlow();
        auditFlow.setStatus(drugPutBillAuditReqDTO.getPass() ? AuditStatusEnum.FINISH.getCode() : AuditStatusEnum.REJECT.getCode());
        LambdaUpdateWrapper<AuditFlow> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AuditFlow::getFlowNo, auditFlowDetail.getFlowNo());
        auditFlowService.update(auditFlow, wrapper);

        return ApiResult.success();
    }

}
